<template>
  <el-form ref="formRef" :model="formData" label-width="120px">
    <base-layout
      :dialog-close-confirm="false"
      :dialog-title="dialogTitle"
      :dialog-visible="dialogVisible"
      visibleContent2
      @dialog-close="dialogClose">
      <template #searchPanel>
        <el-row>
          <el-col :span="12">采购基础信息</el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购编号" prop="code">
              <el-input v-model="formData.code" disabled  readonly="readonly" placeholder="自动生成"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购门店" prop="storeId">
              <job-shop v-model="formData.storeId" :defaultStoreId="$route.params.id != 0" class="w-100"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购供应商" prop="purchaseSupplierId">
              <el-select v-model="formData.purchaseSupplierId" @change="supplierChange" placeholder="请选择" class="w-100">
                <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.supplierName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择" class="w-100">
                <el-option v-for="item in dict['采购类型']" :key="item.index" :value="item.value" :label="item.text"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单据日期" prop="receiptsTime">
              <el-date-picker type="datetime" v-model="formData.receiptsTime" disabled value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择" class="w-100"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商联系人" prop="supplierUserName">
              <el-input placeholder="请输入" v-model="formData.supplierUserName"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商联系方式"  prop="supplierPhone">
              <el-input placeholder="请输入" v-model="formData.supplierPhone"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="采购备注" prop="remark">
              <el-input type="textarea" v-model="formData.remark" :rows="6" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel>
        <el-row>
          <el-col :span="12">采购人员</el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购人员" prop="userName">
              <user-select v-model="formData.userName" :store-id="formData.storeId" @change="userNameHChange" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式" prop="phone">
              <el-input placeholder="请输入" v-model="formData.phone"/>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel2>
        <el-row type="flex" align="middle">
          <el-col :span="12">采购精品列表</el-col>
          <el-col class="text-right" :span="12">
            <el-button type="primary" icon="el-icon-plus" @click="addProductHandle">添加采购精品</el-button>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <!-- @size-change="handleSizeChange"
          @current-change="handleCurrentChange" -->
        <data-table
          has-action
          :is-show-page="false"
          :value="formData.partsList"
          :table-column-attributes="tableColumns"
          :width="160"
        >
          <template #action="{row, $index}">
            <i class="el-icon-delete" title="删除" style="cursor: pointer;"  @click="handleDataDelete(row, $index)"></i>
          </template>
          <div class="total-count" slot="allNum">
            <span>精品总金额:</span><span class="money-value">￥{{formData.amount}}</span>
            <span class="ml-20">总优惠金额:</span><span class="money-value">￥{{formData.freePrice}}</span>
            <span class="ml-20">配件总数:</span><span class="count-value">{{formData.partsNum}}</span>
          </div>
        </data-table>
        <div class="text-right mt-10">
          <span class="total-count">
            采购总金额:<span class="money-value">￥{{formData.amount}}</span>
          </span>
          <el-button v-permission="$route.params.id == 0 ? authConfig.add : authConfig.edit" class="ml-20" type="success"  @click="submitHandle">{{$route.params.id == 0 ? '新增' : '更新'}}采购单</el-button>
        </div>
      </template>
      <template #dialog>
        <select-product-form v-if="showProductTable"  @select="confirmSelectHandle" :supplier-id="formData.purchaseSupplierId"/>
        <EmployeeTable
          v-if="showEmployeeTable"
          :store-id="formData.storeId"
          @select-item="employeSelect"
        />
      </template>
    </base-layout>
  </el-form>
</template>

<script>
import BaseLayout from '@/views/layout/Base'
import DataTable from '@/components/DataTable'
import { JobShop } from '@/components/index'

import SelectProductForm from '@/components/CommonForm/SelectProductForm'
import UserSelect from '@/components/CommonForm/UserSelect'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import { getSupplierByStorId, details } from '@/api/after-sale/systemManage/supplier'
import { save, update, editDetailById, getPurchaseCode } from '@/api/pre-sale/boutiquePurchase/apply'

export default {
  components: { JobShop, BaseLayout, DataTable, SelectProductForm, UserSelect },
  data() {
    this.authConfig = {
      add: 'purchaseRecord:save',
      edit: 'purchaseRecord:update'
    }

    return {
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        code: '',
        storeId: '',
        purchaseSupplierId: '',
        supplierUserName: '',
        supplierPhone: '',
        receiptsTime: parseTimeToYMDHMS(new Date()),
        type: '',
        remark: '',
        userName: '',
        phone: '',
        amount: 0, // 总金额
        freePrice: 0, // 优惠总金额
        partsNum: 0, // 配件数量
        partsList: []
      },
      tableColumns: [
        { name: '精品编号', value: 'partsCode', type: 'text' },
        { name: '精品名称', value: 'partsName', type: 'text' },
        { name: '一级类别', value: 'partsType', type: 'text' },
        { name: '二级类别', value: 'partsUnit', type: 'text' },
        { name: '采购数量', value: 'purchaseNum', type: 'inputNumber', minFiled: 1, action: this.calcData },
        { name: '采购单价', value: 'purchasePrice', type: 'inputNumber', action: this.calcData },
        { name: '优惠', value: 'freePrice', type: 'inputNumber', action: this.calcData },
        { name: '总金额', value: 'amount', type: 'text' }
      ],
      supplierList: [],
      showProductTable: false, // 显示精品选择
      showEmployeeTable: false // 显示员工选择
    }
  },
  computed: {
    tableDataMap() {
      const map = {}
      this.formData.partsList.forEach((item, index) => {
        map[item.partsId] = index
      })
      return map
    },
    storeId() {
      return this.formData.storeId
    }
  },
  watch: {
    storeId() {
      this.requestSupplierList()
    }
  },
  methods: {
    addProductHandle() {
      this.dialogTitle = '精品选择'
      this.dialogVisible = true
      this.showProductTable = true
    },
    // 计算当前数据
    calcData(row) {
      const { purchaseNum, purchasePrice, freePrice } = row
      row.amount = purchaseNum * purchasePrice - freePrice
      this.calcCountData()
    },
    // 统计所有数据
    calcCountData() {
      let amount = 0 // 总金额
      let freePrice = 0 // 优惠总金额
      let partsNum = 0 // 总数量

      this.formData.partsList.forEach(item => {
        amount += item.amount || 0
        freePrice += item.freePrice || 0
        partsNum += item.purchaseNum || 0
      })
      this.formData.amount = amount
      this.formData.freePrice = freePrice
      this.formData.partsNum = partsNum
    },
    handleDataDelete(row, $index) {
      this.formData.partsList.splice($index, 1)
      this.calcCountData()
    },
    submitHandle() {
      const method = this.$route.params.id == 0 ? save : update
      this.$refs.formRef.validate(valid => {
        if (valid) {
          method(this.formData).then(res => {
            const length = this.$store.state.tagsView.visitedViews.length
            this.$store.dispatch('delVisitedViews', this.$route)
            if (length == 2) {
              this.$router.replace({ path: '/' })
            } else {
              this.$router.go(-1)
            }
          })
        }
      })
    },
    // 供应商改变
    supplierChange(value) {
      this.formData.supplierUserName = ''
      this.formData.supplierPhone = ''
      this.requestSupplierDetail(value)
    },
    // 负责人选择
    userNameHChange(item) {
      this.formData.userName = item.userName
      this.formData.phone = item.phone
    },
    // 商品确认选择
    confirmSelectHandle(selection) {
      const tableList = []
      selection.forEach(item => {
        if (!this.tableDataMap[item.id]) {
          tableList.push({
            amount: item.currentPrice,
            freePrice: 0,
            partsCode: item.orderNo,
            partsId: item.id,
            partsName: item.name,
            partsType: item.appLargeOne, // 一级分类名称
            partsUnit: item.appLargeTwo, // 二级分类名称
            purchaseNum: 1,
            purchasePrice: item.currentPrice,
            internalNum: 0
          })
        }
      })
      this.formData.partsList.push(...tableList)
      this.calcCountData()
      this.dialogClose()
    },
    dialogClose() {
      this.showProductTable = null
      this.showEmployeeTable = null
      this.dialogVisible = false
    },
    // 请求编辑采购详情
    requestEditDetail(id) {
      editDetailById(id).then(res => {
        Object.assign(this.formData, res.data)
      })
    },
    // 请求编码
    requestPurchaseCode() {
      getPurchaseCode().then(res => {
        this.formData.code = res.data
      })
    },
    // 请求 供应商
    requestSupplierList() {
      const { storeId } = this.formData
      if (!storeId) {
        return
      }
      getSupplierByStorId(this.storeId, '精品供应商').then(res => {
        this.supplierList = res.data || []
        if (!this.supplierList.find(item => item.id == this.formData.purchaseSupplierId)) {
          this.formData.purchaseSupplierId = ''
          this.formData.supplierUserName = ''
          this.formData.supplierPhone = ''
        }
      })
    },
    // 请求供应商详情
    requestSupplierDetail(id) {
      details(id).then(res => {
        this.formData.supplierUserName = res.data.contactName
        this.formData.supplierPhone = res.data.contactPhone
      })
    }
  },
  created() {
    this.dict = getDict(['采购类型'])
  },
  mounted() {
    const { id } = this.$route.params
    if (id != 0) {
      this.requestEditDetail(id)
    } else {
      this.requestPurchaseCode()
    }
  }
}
</script>

<style>

</style>
